import random


def get_imei():
    """
    TAC:Type Allocation Code，类型分配码，由8位数字组成（早期是6位），是区分手机品牌和型号的编码，该代码由GSMA及其授权机构分配。其中TAC码前两位又是分配机构标识（Reporting Body Identifier），是授权IMEI码分配机构的代码，如01为美国CTIA，35为英国BABT，86为中国TAF。
    FAC:Final Assembly Code，最终装配地代码，由2位数字构成，仅在早期TAC码为6位的手机中存在，所以TAC和FAC码合计一共8位数字。FAC码用于生产商内部区分生产地代码。
    SNR:Serial Number，序列号，由第9位开始的6位数字组成，区分每部手机的生产序列号。
    """
    TAC = [8, 6] + [random.randint(1, 9) for _ in range(6)]
    SNR = [random.randint(1, 9) for _ in range(6)]
    check = TAC + SNR
    evens = [str(n * 2) for n in check[1::2]]
    sums = []
    for i in evens:
        if len(i) >= 2:
            i = list(i)
            sums += [int(n) for n in i]
        else:
            sums.append(int(i))
    checks = ((sum(sums) + sum(check[::2])) // 10 + 1) * 10 - (sum(sums) + sum(check[::2]))
    if checks == 10:
        checks = 0
    imei = ''.join([str(n) for n in check]) + str(checks)
    if isImei(imei):
        return imei
    else:
        raise Exception('IMEI 生成错误')


def isImei(imei):
    try:
        imeiChar = list(imei)  # .toCharArray()
        resultInt = 0
        i = 0
        while i < len(imeiChar) - 1:
            a = int(imeiChar[i])
            i += 1
            temp = int(imeiChar[i]) * 2
            b = (temp - 9, temp)[temp < 10]  # temp if temp < 10 else temp - 9
            resultInt += a + b
            i += 1
        resultInt %= 10
        resultInt = (10 - resultInt, 0)[resultInt == 0]
        crc = int(imeiChar[14])
        return resultInt == crc
    except:
        return False


if __name__ == '__main__':
    imei = get_imei()
    print(imei)
